<template>
  <div class="login-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>系统登录</span>
        </div>
      </template>
      <el-form :model="loginForm" status-icon :rules="loginRules" ref="loginFormRef" label-width="0">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            prefix-icon="el-icon-user"
            placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            prefix-icon="el-icon-lock"
            type="password"
            placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { getActivePinia } from 'pinia';

// 在 setup 函数中
console.log("==============",getActivePinia()); // 应该输出 Pinia 实例，而不是 undefined
import { computed, onMounted,ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { usePermissionStore } from '@/stores/permission'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const permissionStore = usePermissionStore()


const loginFormRef = ref(null)
const loginForm = reactive({
  username: 'admin',
  password: '123456'
})

const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ]
})

const loading = ref(false)

const handleLogin = async () => {
  loginFormRef.value.validate(async valid => {
    if (valid) {
      loading.value = true
      try {
        // 调用 userStore 的登录方法
        await userStore.login(loginForm)

        // 获取用户权限并生成动态路由
        await permissionStore.generateRoutes(userStore.menus)

        // 登录成功，跳转到首页
        ElMessage.success('登录成功')
        await router.push({path: '/'})
      } catch (error) {
        // 登录失败，显示错误信息
        ElMessage.error(error.message || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.box-card {
  width: 400px;
}
</style>
